package com.ruoyi.generator.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.GenConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.core.text.CharsetKit;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.generator.config.GenConfig;
import com.ruoyi.generator.domain.GenTable;
import com.ruoyi.generator.domain.GenTableColumn;
import com.ruoyi.generator.domain.TableColumn;
import com.ruoyi.generator.mapper.GenTableColumnMapper;
import com.ruoyi.generator.mapper.GenTableMapper;
import com.ruoyi.generator.util.GenUtils;
import com.ruoyi.generator.util.ModuleReqPrefixUtil;
import com.ruoyi.generator.util.VelocityInitializer;
import com.ruoyi.generator.util.VelocityUtils;
import com.ruoyi.system.mapper.SysMenuMapper;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.system.service.ISysMenuService;
import com.zgl.youshuda.core.utils.SnowFlakeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.sql.SQLSyntaxErrorException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 业务 服务层实现
 *
 * @author ruoyi
 */
@Service
public class GenTableServiceImpl implements IGenTableService
{
    private static final Logger log = LoggerFactory.getLogger(GenTableServiceImpl.class);

    @Autowired
    private GenTableMapper genTableMapper;

    @Autowired
    private GenTableColumnMapper genTableColumnMapper;

    @Autowired
    private ISysDictTypeService dictTypeService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private SysMenuMapper menuService;

    /**
     * 查询业务信息
     *
     * @param id 业务ID
     * @return 业务信息
     */
    @Override
    public GenTable selectGenTableById(Long id)
    {
        GenTable genTable = genTableMapper.selectGenTableById(id);
        setTableFromOptions(genTable);
        return genTable;
    }

    /**
     * 根据ClassName获取请求路径
     *
     * @param className
     * @return
     */
    public List<Map<String,String>> getPrefixUrl(String className){
        return genTableMapper.getPrefixUrl(className);
    }

    /**
     * 查询业务列表
     *
     * @param genTable 业务信息
     * @return 业务集合
     */
    @Override
    public List<GenTable> selectGenTableList(GenTable genTable)
    {
        return genTableMapper.selectGenTableList(genTable);
    }

    /**
     * 查询据库列表
     *
     * @param genTable 业务信息
     * @return 数据库表集合
     */
    @Override
    public List<GenTable> selectDbTableList(GenTable genTable)
    {
        return genTableMapper.selectDbTableList(genTable);
    }

    /**
     * 查询据库列表
     *
     * @param tableNames 表名称组
     * @return 数据库表集合
     */
    @Override
    public List<GenTable> selectDbTableListByNames(String[] tableNames)
    {
        return genTableMapper.selectDbTableListByNames(tableNames);
    }

    /**
     * 查询所有表信息
     *
     * @return 表信息集合
     */
    @Override
    public List<GenTable> selectGenTableAll()
    {
        return genTableMapper.selectGenTableAll();
    }

    /**
     * 修改业务
     *
     * @param genTable 业务信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGenTable(GenTable genTable) throws Exception
    {
        //业务名与类名一致，方便查找
        genTable.setBusinessName(genTable.getClassName());
        String options = JSON.toJSONString(genTable.getParams());
        genTable.setOptions(options);
        int row = genTableMapper.updateGenTable(genTable);
        if (row > 0)
        {
            TableColumn tableColumn=null;

            //标记是否可能为视图
            boolean isView=false;

            try{
                /**
                 * 修改表注释信息
                 */
                tableColumn=new TableColumn();
                //表名
                tableColumn.setTableName(genTable.getTableName());
                //表描述
                tableColumn.setColumnDesc(genTable.getTableComment());
                genTableMapper.updateTableInfo(tableColumn);
            }catch (Exception e){
                log.error("模块信息保存失败，可能原因是【视图】可忽视：",e.getMessage());

                /**
                 * 修改表字段信息
                 */
                for (GenTableColumn cenTableColumn : genTable.getColumns()) {
                    /**
                     * 修改模块字段信息
                     */
                    genTableColumnMapper.updateGenTableColumn(cenTableColumn);
                }
                isView=true;
            }

            /**
             * 不为视图时，修改对应字段信息
             */
            if(!isView) {

                /**
                 * 判断基本字段是否存在
                 */
                Map<String, Boolean> baseColumnExistTarget = new HashMap<>();
                /**
                 * 基本字段
                 */
                List<String> baseColumn = Arrays.asList(new String[]{"id", "create_by", "create_time", "update_by", "update_time", "del_flag","remark"});

                /**
                 * 修改表字段信息
                 */
                for (GenTableColumn cenTableColumn : genTable.getColumns()) {

                    /**
                     * 收集存在的基本字段
                     */
                    if (baseColumn.contains(cenTableColumn.getColumnName())) {
                        baseColumnExistTarget.put(cenTableColumn.getColumnName(), true);
                    }

                    /**
                     * 修改模块字段信息
                     */
                    genTableColumnMapper.updateGenTableColumn(cenTableColumn);
                    /**
                     * 修改表结构信息
                     */
                    tableColumn = new TableColumn();
                    //表名
                    tableColumn.setTableName(genTable.getTableName());
                    //字段名
                    tableColumn.setColumnName(cenTableColumn.getColumnName());
                    //字段类型
                    tableColumn.setColumnType(cenTableColumn.getColumnType());
                    //是否主键（1是）
                    tableColumn.setIsPk(cenTableColumn.getIsPk());
                    //字段注释
                    String columnDesc = cenTableColumn.getColumnComment();
                    if (StringUtils.isNotEmpty(cenTableColumn.getColumnDesc())) {
                        columnDesc = cenTableColumn.getColumnComment() + "__" + cenTableColumn.getColumnDesc();
                    }
                    tableColumn.setColumnDesc(columnDesc);
                    //默认值
                    tableColumn.setColumnDefault(cenTableColumn.getColumnDefault());

                    genTableColumnMapper.updateTableColumnInfo(tableColumn);
                }

                /**
                 * 新增不存在的基础字段
                 */
                for(String noExists:baseColumn){
                    if(baseColumnExistTarget.get(noExists)==null){
                        switch (noExists) {
                            case "id":
                                gengerIdColumn(genTable);
                                break;
                            case "create_by":
                                gengerAddUserColumn(genTable);
                                break;
                            case "create_time":
                                gengerAddTimeColumn(genTable);
                                break;
                            case "update_by":
                                gengerUpdateUserColumn(genTable);
                                break;
                            case "update_time":
                                gengerUpdateTimeColumn(genTable);
                                break;
                            case "del_flag":
                                gengerDelMarkColumn(genTable);
                                break;
                            case "remark":
                                gengerRemarkColumn(genTable);
                                break;
                        }
                    }
                }

            }

        }

        /**
         * 保存菜单、按钮配置信息
         */
        updateMenuBtnInfo(genTable);
    }

    /**
     * 保存菜单、按钮配置信息
     */
    private void updateMenuBtnInfo(GenTable genTable){
        // 设置主子表信息
        setSubTable(genTable);
        // 设置主键列信息
        setPkColumn(genTable);
        VelocityInitializer.initVelocity();
        VelocityContext context = VelocityUtils.prepareContext(genTable);
        String moduleName = String.valueOf(context.get("moduleName"));

        Map<String, String> moduleConfig = new HashMap<>();
        moduleConfig.put("functionName", String.valueOf(context.get("functionName")));
        moduleConfig.put("parentMenuId", String.valueOf(context.get("parentMenuId")));
        moduleConfig.put("businessName", String.valueOf(context.get("businessName")));
        moduleConfig.put("permissionPrefix", String.valueOf(context.get("permissionPrefix")));
        moduleConfig.put("author", String.valueOf(context.get("author")));
        moduleConfig.put("moduleName", moduleName);
        moduleConfig.put("vueModelPath", moduleName);
        String _moduleName= ModuleReqPrefixUtil.getModuleRequestPrefix(moduleName);
        moduleConfig.put("vueComponent", _moduleName+"/"+String.valueOf(context.get("businessName"))+"/index");

        Long menuId = 0L;
        synchronized (GenTableServiceImpl.class) {
            //需要被同步的代码块
            menuId = genTableMapper.getMaxId();
            menuId += 1;
        }

        moduleConfig.put("menuId", String.valueOf(menuId));
        //菜单顺序
        moduleConfig.put("orderNum", "1");
        //菜单是否隐藏
        String visible="0";
        //菜单
        /**
         * 获取之前菜单配置信息
         */
        List<Map<String, Object>> oldMenuInfo = genTableMapper.getOldMenuInfo(moduleConfig);
        if(oldMenuInfo!=null && oldMenuInfo.size()>0){
            //之前菜单id
            moduleConfig.put("oldMenuId", String.valueOf(oldMenuInfo.get(0).get("menu_id")));
            //菜单顺序
            moduleConfig.put("orderNum", String.valueOf(oldMenuInfo.get(0).get("order_num")));
            //菜单名称
            moduleConfig.put("functionName", String.valueOf(oldMenuInfo.get(0).get("menu_name")));
            //菜单是否隐藏
            visible=String.valueOf(oldMenuInfo.get(0).get("visible"));
            /**
             * 1.删除菜单按钮
             */
            genTableMapper.delMenuBtn(moduleConfig);
            /**
             * 2.删除菜单
             */
            genTableMapper.delMenu(moduleConfig);
        }
        //菜单是否隐藏
        moduleConfig.put("visible", visible);
        /**
         * 3.新增菜单
         */
        genTableMapper.addMenu(moduleConfig);
        //按钮
        //查询
        Map<String, String> addBtnConfig = moduleConfig;
        addBtnConfig.put("title", "查询");
        addBtnConfig.put("permi", "query");
        genTableMapper.addBtn(addBtnConfig);
        //新增
        addBtnConfig = moduleConfig;
        addBtnConfig.put("title", "新增");
        addBtnConfig.put("permi", "add");
        genTableMapper.addBtn(addBtnConfig);
        //修改
        addBtnConfig = moduleConfig;
        addBtnConfig.put("title", "修改");
        addBtnConfig.put("permi", "edit");
        genTableMapper.addBtn(addBtnConfig);
        //删除
        addBtnConfig = moduleConfig;
        addBtnConfig.put("title", "删除");
        addBtnConfig.put("permi", "remove");
        genTableMapper.addBtn(addBtnConfig);
        //导出
        addBtnConfig = moduleConfig;
        addBtnConfig.put("title", "导入");
        addBtnConfig.put("permi", "import");
        genTableMapper.addBtn(addBtnConfig);
        //导出
        addBtnConfig = moduleConfig;
        addBtnConfig.put("title", "导出");
        addBtnConfig.put("permi", "export");
        genTableMapper.addBtn(addBtnConfig);
    }


    /**
     * ID
     * @param genTable
     */
    private void gengerIdColumn(GenTable genTable)throws Exception{
        /**
         * 添加字段到gen_table_column
         */
        GenTableColumn column =new GenTableColumn();
        //字段名称
        column.setColumnName("id");
        //是否主键
        column.setIsPk("1");
        //字段描述
        column.setColumnComment("ID");
        //字段描述
        column.setColumnDesc("ID");
        column.setIsIncrement("0");
        //字段类型
        column.setColumnType("bigint");
        gengerBaseColumn(genTable,column);
    }

    /**
     * 新增用户
     * @param genTable
     */
    private void gengerAddUserColumn(GenTable genTable)throws Exception{
        /**
         * 添加字段到gen_table_column
         */
        GenTableColumn column =new GenTableColumn();
        //字段名称
        column.setColumnName("create_by");
        //是否主键
        column.setIsPk("0");
        //字段描述
        column.setColumnComment("新增用户");
        //字段描述
        column.setColumnDesc("新增用户");
        column.setIsIncrement("0");
        //字段类型
        column.setColumnType("varchar(50)");
        gengerBaseColumn(genTable,column);
    }

    /**
     * 新增时间
     * @param genTable
     */
    private void gengerAddTimeColumn(GenTable genTable)throws Exception{
        /**
         * 添加字段到gen_table_column
         */
        GenTableColumn column =new GenTableColumn();
        //字段名称
        column.setColumnName("create_time");
        //是否主键
        column.setIsPk("0");
        //字段描述
        column.setColumnComment("添加时间");
        //字段描述
        column.setColumnDesc("添加时间");
        column.setIsIncrement("0");
        //字段类型
        column.setColumnType("timestamp");
        //默认值
        column.setColumnDefault("CURRENT_TIMESTAMP");

        gengerBaseColumn(genTable,column);
    }

    /**
     * 修改用户
     * @param genTable
     */
    private void gengerUpdateUserColumn(GenTable genTable)throws Exception{
        /**
         * 添加字段到gen_table_column
         */
        GenTableColumn column =new GenTableColumn();
        //字段名称
        column.setColumnName("update_by");
        //是否主键
        column.setIsPk("0");
        //字段描述
        column.setColumnComment("修改用户");
        //字段描述
        column.setColumnDesc("修改用户");
        column.setIsIncrement("0");
        //字段类型
        column.setColumnType("varchar(50)");
        gengerBaseColumn(genTable,column);
    }

    /**
     * 修改时间
     * @param genTable
     */
    private void gengerUpdateTimeColumn(GenTable genTable)throws Exception{
        /**
         * 添加字段到gen_table_column
         */
        GenTableColumn column =new GenTableColumn();
        //字段名称
        column.setColumnName("update_time");
        //是否主键
        column.setIsPk("0");
        //字段描述
        column.setColumnComment("修改时间");
        //字段描述
        column.setColumnDesc("修改时间");
        column.setIsIncrement("0");
        //字段类型
        column.setColumnType("timestamp");
        //默认值
        column.setColumnDefault("CURRENT_TIMESTAMP");

        gengerBaseColumn(genTable,column);
    }

    /**
     * 删除标记
     * @param genTable
     */
    private void gengerDelMarkColumn(GenTable genTable)throws Exception{
        /**
         * 添加字段到gen_table_column
         */
        GenTableColumn column =new GenTableColumn();
        //字段名称
        column.setColumnName("del_flag");
        //是否主键
        column.setIsPk("0");
        //字段描述
        column.setColumnComment("删除标记");
        //字段描述
        column.setColumnDesc("删除标记");
        column.setIsIncrement("0");
        //字段类型
        column.setColumnType("varchar(10)");
        gengerBaseColumn(genTable,column);
    }

    /**
     * 备注字段
     * @param genTable
     */
    private void gengerRemarkColumn(GenTable genTable)throws Exception{
        /**
         * 添加字段到gen_table_column
         */
        GenTableColumn column =new GenTableColumn();
        //字段名称
        column.setColumnName("remark");
        //是否主键
        column.setIsPk("0");
        //字段描述
        column.setColumnComment("备注");
        //字段描述
        column.setColumnDesc("备注");
        column.setIsIncrement("0");
        //字段类型
        column.setColumnType("varchar(255)");
        gengerBaseColumn(genTable,column);
    }

    /**
     * 添加默认表默认字段
     * @param genTable
     */
    private void gengerBaseColumn(GenTable genTable, GenTableColumn column) throws Exception{
        /**
         * 添加字段到gen_table_column
         */
        //排序
        column.setSort(genTable.getColumns().size()+1);
        //初始化字段属性
        GenUtils.initColumnField(column, genTable);

        genTableColumnMapper.insertGenTableColumn(column);

        /**
         * 修改表结构信息
         */
        TableColumn tableColumn=new TableColumn();
        //表名
        tableColumn.setTableName(genTable.getTableName());
        //字段名
        tableColumn.setColumnName(column.getColumnName());
        //字段类型
        tableColumn.setColumnType(column.getColumnType());
        //字段注释
        tableColumn.setColumnDesc(column.getColumnDesc());
        //是否主键
        tableColumn.setIsPk(column.getIsPk());
        //默认值
        tableColumn.setColumnDefault(column.getColumnDefault());

        genTableColumnMapper.addTableColumnInfo(tableColumn);
    }

    /**
     * 删除业务对象
     *
     * @param tableIds 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public void deleteGenTableByIds(Long[] tableIds)
    {
        List<GenTable> genTables = genTableMapper.selectGenTableByIds(tableIds);
        if(genTables!=null && genTables.size()>0){
            for(GenTable item: genTables){
                //删除表单设计
                genTableMapper.deleteFromBuildConfig(item.getClassName());
                genTableMapper.deleteFromBuildConfigOptions(item.getClassName());
                genTableMapper.deleteFromBuildConfigRule(item.getClassName());
                //删除菜单
                menuService.deleteMenuByPermsPrefix(item.getModuleName(),item.getClassName());
            }
        }
        genTableMapper.deleteGenTableByIds(tableIds);
        genTableColumnMapper.deleteGenTableColumnByIds(tableIds);
    }

    /**
     * 导入表结构
     *
     * @param tableList 导入表列表
     */
    @Override
    @Transactional
    public void importGenTable(List<GenTable> tableList)
    {
        String operName = SecurityUtils.getUsername();
        try
        {
            for (GenTable table : tableList)
            {
                String tableName = table.getTableName();
                GenUtils.initTable(table, operName);
                int row = genTableMapper.insertGenTable(table);
                if (row > 0)
                {
                    // 保存列信息
                    List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
                    for (GenTableColumn column : genTableColumns)
                    {
                        GenUtils.initColumnField(column, table);
                        /**
                         * 将数据库表字段备注拆出来
                         */
                        if(column.getColumnComment().indexOf("__")>-1){
                            String[] s = column.getColumnComment().split("__");
                            //中文字段名
                            column.setColumnComment(s[0]);
                            //字段描述
                            column.setColumnDesc(s[1]);
                        }
                        /**
                         * 判断备注中是否有指定组件，如有则指定对应的htmlType
                         */
                        dealColumnOptions(tableName,column);

                        genTableColumnMapper.insertGenTableColumn(column);
                    }
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            throw new ServiceException("导入失败：" + e.getMessage());
        }
    }

    /**
     * 判断备注中是否有指定组件，如有则指定对应的htmlType
     * 规则：
     * 	以S[..选项值..]  下拉框
     * 	以R[..选项值..]  单选框
     * 	以C[..选项值..]  复选框
     * 选项值：以“_”分隔区分多个选项，每个选项以“:”分隔区分 值与描述
     */
    private void dealColumnOptions(String tableName,GenTableColumn column){

        if(StringUtils.isEmptyIncludeNull(column.getColumnDesc())){
            return;
        }
        String columnDesc=column.getColumnDesc();
        //选项字符串信息
        String optionStr =null;
        if(columnDesc.indexOf("S[")>-1){
            column.setHtmlType(GenConstants.HTML_SELECT);
            optionStr = StringUtils.substringBetween(columnDesc, "S[", "]");
        }
        if(columnDesc.indexOf("R[")>-1){
            column.setHtmlType(GenConstants.HTML_RADIO);
            optionStr = StringUtils.substringBetween(columnDesc, "R[", "]");
        }
        if(columnDesc.indexOf("C[")>-1){
            column.setHtmlType(GenConstants.HTML_CHECKBOX);
            optionStr = StringUtils.substringBetween(columnDesc, "C[", "]");
        }
        if(StringUtils.isEmptyIncludeNull(optionStr)){
            return;
        }
        /**
         * 字典信息
         */
        SysDictType dictType=new SysDictType();
        //字典名称
        dictType.setDictName(column.getColumnComment());
        dictType.setDictType("dict_"+tableName+"_"+column.getColumnName());
        dictType.setStatus("0");
        if (!dictTypeService.checkDictTypeUnique(dictType)){
            //记录到当前字段
            column.setDictType(dictType.getDictType());
            return;
        }
        dictTypeService.insertDictType(dictType);
        /**
         * 选项信息
         */
        String[] optionItems = optionStr.split("_");
        for(int i=0;i<optionItems.length;i++){
            if(optionItems[i].indexOf(":")==-1){
                continue;
            }
            String[] _option=optionItems[i].split(":");
            SysDictData dict = new SysDictData();
            //字典类型
            dict.setDictType(dictType.getDictType());
            //数据标签
            dict.setDictLabel(_option[1]);
            //数据键值
            dict.setDictValue(_option[0]);
            //显示排序
            dict.setDictSort((long) i);
            //状态
            dict.setStatus("0");
            dictDataService.insertDictData(dict);
        }
        //记录到当前字段
        column.setDictType(dictType.getDictType());
    }

    /**
     * 预览代码
     *
     * @param tableId 表编号
     * @return 预览数据列表
     */
    @Override
    public Map<String, String> previewCode(Long tableId)
    {
        Map<String, String> dataMap = new LinkedHashMap<>();
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableById(tableId);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);
        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates)
        {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Constants.UTF8);
            tpl.merge(context, sw);
            dataMap.put(template, sw.toString());
        }
        return dataMap;
    }

    /**
     * 生成代码（下载方式）
     *
     * @param tableName 表名称
     * @return 数据
     */
    @Override
    public byte[] downloadCode(String tableName)
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        generatorCode(tableName, zip);
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /**
     * 生成代码（自定义路径）
     *
     * @param tableName 表名称
     */
    @Override
    public void generatorCode(String tableName)
    {
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableByName(tableName);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates)
        {
//            if (!StringUtils.containsAny(template, "sql.vm"))
//            {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Constants.UTF8);
            tpl.merge(context, sw);
            try
            {
                String path = getGenPath(table, template);
                log.info("代码生成table："+table.getTableName()+"，template："+template+"，path:"+path);
                FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8);
            }
            catch (IOException e)
            {
//                throw new CustomException("渲染模板失败，表名：" + table.getTableName());
            }
//            }
        }
    }

    /**
     * 同步数据库
     *
     * @param tableName 表名称
     */
    @Override
    @Transactional
    public void synchDb(String tableName)
    {
        GenTable table = genTableMapper.selectGenTableByName(tableName);
        List<GenTableColumn> tableColumns = table.getColumns();
        Map<String, GenTableColumn> tableColumnMap = tableColumns.stream().collect(Collectors.toMap(GenTableColumn::getColumnName, Function.identity()));

        List<GenTableColumn> dbTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
        if (StringUtils.isEmpty(dbTableColumns))
        {
            throw new ServiceException("同步数据失败，原表结构不存在");
        }
        List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());

        dbTableColumns.forEach(column -> {
            GenUtils.initColumnField(column, table);

            /**
             * 将数据库表字段备注拆出来
             */
            if(column.getColumnComment().indexOf("__")>-1){
                String[] s = column.getColumnComment().split("__");
                //中文字段名
                column.setColumnComment(s[0]);
                //字段描述
                column.setColumnDesc(s[1]);
            }

            if (tableColumnMap.containsKey(column.getColumnName()))
            {
                GenTableColumn prevColumn = tableColumnMap.get(column.getColumnName());
                column.setColumnId(prevColumn.getColumnId());
                if (column.isList())
                {
                    // 如果是列表，继续保留查询方式/字典类型选项
                    column.setDictType(prevColumn.getDictType());
                    column.setQueryType(prevColumn.getQueryType());
                }
                if (StringUtils.isNotEmpty(prevColumn.getIsRequired()) && !column.isPk()
                        && (column.isInsert() || column.isEdit())
                        && ((column.isUsableColumn()) || (!column.isSuperColumn())))
                {
                    // 如果是(新增/修改&非主键/非忽略及父属性)，继续保留必填/显示类型选项
                    column.setIsRequired(prevColumn.getIsRequired());
                    column.setHtmlType(prevColumn.getHtmlType());
                }
                genTableColumnMapper.updateGenTableColumn(column);
            }
            else
            {
                genTableColumnMapper.insertGenTableColumn(column);
            }
        });

        List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
        if (StringUtils.isNotEmpty(delColumns))
        {
            genTableColumnMapper.deleteGenTableColumns(delColumns);
        }
    }

    /**
     * 批量生成代码（下载方式）
     *
     * @param tableNames 表数组
     * @return 数据
     */
    @Override
    public byte[] downloadCode(String[] tableNames)
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames)
        {
            generatorCode(tableName, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /**
     * 查询表信息并生成代码
     */
    private void generatorCode(String tableName, ZipOutputStream zip)
    {
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableByName(tableName);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates)
        {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Constants.UTF8);
            tpl.merge(context, sw);
            try
            {
                // 添加到zip
                zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
                IOUtils.write(sw.toString(), zip, Constants.UTF8);
                IOUtils.closeQuietly(sw);
                zip.flush();
                zip.closeEntry();
            }
            catch (IOException e)
            {
                log.error("渲染模板失败，表名：" + table.getTableName(), e);
            }
        }
    }

    /**
     * 修改保存参数校验
     *
     * @param genTable 业务信息
     */
    @Override
    public void validateEdit(GenTable genTable)
    {
        if (GenConstants.TPL_TREE.equals(genTable.getTplCategory()))
        {
            String options = JSON.toJSONString(genTable.getParams());
            JSONObject paramsObj = JSON.parseObject(options);
            if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE)))
            {
                throw new ServiceException("树编码字段不能为空");
            }
            else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE)))
            {
                throw new ServiceException("树父编码字段不能为空");
            }
            else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME)))
            {
                throw new ServiceException("树名称字段不能为空");
            }
            else if (GenConstants.TPL_SUB.equals(genTable.getTplCategory()))
            {
                if (StringUtils.isEmpty(genTable.getSubTableName()))
                {
                    throw new ServiceException("关联子表的表名不能为空");
                }
                else if (StringUtils.isEmpty(genTable.getSubTableFkName()))
                {
                    throw new ServiceException("子表关联的外键名不能为空");
                }
            }
        }
    }

    /**
     * 设置主键列信息
     *
     * @param table 业务表信息
     */
    public void setPkColumn(GenTable table)
    {
        for (GenTableColumn column : table.getColumns())
        {
            if (column.isPk())
            {
                table.setPkColumn(column);
                break;
            }
        }
        if (StringUtils.isNull(table.getPkColumn()))
        {
            table.setPkColumn(table.getColumns().get(0));
        }
        if (GenConstants.TPL_SUB.equals(table.getTplCategory()))
        {
            for (GenTableColumn column : table.getSubTable().getColumns())
            {
                if (column.isPk())
                {
                    table.getSubTable().setPkColumn(column);
                    break;
                }
            }
            if (StringUtils.isNull(table.getSubTable().getPkColumn()))
            {
                table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0));
            }
        }
    }

    /**
     * 设置主子表信息
     *
     * @param table 业务表信息
     */
    public void setSubTable(GenTable table)
    {
        String subTableName = table.getSubTableName();
        if (StringUtils.isNotEmpty(subTableName))
        {
            table.setSubTable(genTableMapper.selectGenTableByName(subTableName));
        }
    }

    /**
     * 设置代码生成其他选项值
     *
     * @param genTable 设置后的生成对象
     */
    public void setTableFromOptions(GenTable genTable)
    {
        JSONObject paramsObj = JSON.parseObject(genTable.getOptions());
        if (StringUtils.isNotNull(paramsObj))
        {
            String treeCode = paramsObj.getString(GenConstants.TREE_CODE);
            String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE);
            String treeName = paramsObj.getString(GenConstants.TREE_NAME);
            String parentMenuId = paramsObj.getString(GenConstants.PARENT_MENU_ID);
            String parentMenuName = paramsObj.getString(GenConstants.PARENT_MENU_NAME);

            genTable.setTreeCode(treeCode);
            genTable.setTreeParentCode(treeParentCode);
            genTable.setTreeName(treeName);
            genTable.setParentMenuId(parentMenuId);
            genTable.setParentMenuName(parentMenuName);
        }
    }

    /**
     * 获取代码生成地址
     *
     * @param table 业务表信息
     * @param template 模板文件路径
     * @return 生成地址
     */
    public static String getGenPath(GenTable table, String template)
    {
        String genPath = table.getGenPath();
        if (StringUtils.equals(genPath, "/"))
        {
            return GenConfig.getGenPath() + File.separator + VelocityUtils.getFileName(template, table);
        }
        return genPath + File.separator + VelocityUtils.getFileName(template, table);
    }

    /**
     * 查询表名称业务信息
     *
     * @param tableName 表名称
     * @return 业务信息
     */
    @Override
    public List<Map<String,Object>> getFieldByTabName(String tableName){
        return genTableMapper.getFieldByTabName(tableName);
    }

}
